package com.bangbang.controller;


import com.bangbang.configresult.Result;
import com.bangbang.configresult.ResultEnum;
import com.bangbang.dto.PayDTO;
import com.bangbang.feign.PayServiceFeign;
import com.bangbang.mapper.TbPeopleCourseMapper;
import com.bangbang.mapper.TbPeopleCourseOrderMapper;
import com.bangbang.pojo.TbPeopleCourse;
import com.bangbang.pojo.TbPeopleCourseOrder;
import com.bangbang.util.DateUtilZb;
import com.bangbang.util.IdWorker;
import com.bangbang.util.ReducePriceUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 砍价课程商品订单表 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-08-13
 */
@RestController
@RequestMapping("tbPeopleCourseOrder")
public class TbPeopleCourseOrderController {


    @Autowired
    private TbPeopleCourseOrderMapper tbPeopleCourseOrderMapper;

    @Autowired
    private TbPeopleCourseMapper tbPeopleCourseMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PayServiceFeign payServiceFeign;

    //    用户点击砍价,生成订单,结束时间到,如果砍价成功,拿到砍的金额,并查找原价减去,然后用户点击支付
//    调接口去支付,支付成功添加流水号,把金额和订单号放进去,并且去减库存,砍价不成功,我们就返回砍价失败,并逻辑删除订单,

    //   用户点击我要砍价 砍价
    @ApiOperation(value = "砍价课程生成用户订单方法") //  接口文档方法名
    @ApiImplicitParams({            //  接口文档  解释参数
            @ApiImplicitParam(name = "pid",value = "砍价课程实体类",required = true,paramType = "query"),
    })
    @PostMapping
    public Result OrderToGenerate(@RequestParam("pid") Long pid) throws ParseException {

        QueryWrapper<TbPeopleCourse> peopleCourseQueryWrapper = new QueryWrapper<>();
        peopleCourseQueryWrapper.eq("peo_id", pid);
        TbPeopleCourse tbPeopleCourse = tbPeopleCourseMapper.selectOne(peopleCourseQueryWrapper);

        Object o = redisTemplate.boundValueOps("8ac5cfcb-4bc3-4050-aef5-f0ef18e0128c").get();
        String s1 = o.toString();
        Long userId = Long.valueOf(s1);

        IdWorker idWorker = new IdWorker();
        long l = idWorker.nextId();
        //计算砍后价格
        BigDecimal peoCouPrice = tbPeopleCourse.getPeoCouPrice();
        BigDecimal peoPrice = tbPeopleCourse.getPeoPrice();
        // 后看价格
        BigDecimal subtract = peoPrice.subtract(peoCouPrice);

        DateUtilZb dateUtilZb = new DateUtilZb();
        DateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置时间格式
        String time=sdf.format(new Date());
        String s = dateUtilZb.addDate(time, 2);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date overTime = simpleDateFormat.parse(s);
        TbPeopleCourseOrder tbPeopleCourseOrder = new TbPeopleCourseOrder();
        tbPeopleCourseOrder.setPcoName(tbPeopleCourse.getPeoCouId())
                .setPcoStartTime(new Date())
                .setPcoEndTime(overTime)
                .setPcoPrice(subtract)
                .setPcoRawPrice(peoPrice)
                .setPcoPurchasePerson(tbPeopleCourse.getPeoPeople())
                .setPcoPicture(tbPeopleCourse.getProPicture())
                .setPcoIntroduce(tbPeopleCourse.getPeoContent())
                .setPcoCommoncourseId(tbPeopleCourse.getPeoCommoncourseId())
                .setPcoOrderId(l)
                .setPcoUserId(userId)
                .setPcoPeopleCourserId(tbPeopleCourse.getPeoId());
        tbPeopleCourseOrderMapper.insert(tbPeopleCourseOrder);
        return Result.buildResult(ResultEnum.SUCCESS);
    }



    //    用户分享,帮他砍价 修改订单状态
    @ApiOperation(value = "砍价,减金额方法") //  接口文档方法名
    @ApiImplicitParams({            //  接口文档  解释参数
            @ApiImplicitParam(name = "orderId",value = "订单号",required = true,paramType = "query"),
            @ApiImplicitParam(name = "peopleId",value = "砍价课程id",required = true,paramType = "query"),
            @ApiImplicitParam(name = "userId",value = "砍价用户的id",required = true,paramType = "query"),
    })
    @PostMapping("subtraction")
    public Result subtraction(@RequestParam Long userId,@RequestParam Long peopleId,@RequestParam Long orderId){
//          用户id 放入redis,如果砍果就返回给用户砍过了已经
        redisTemplate.boundValueOps("user").set(userId);
        if (userId == redisTemplate.boundValueOps("user").get()){
            return Result.buildResult(ResultEnum.ERROR).setResult("您已经砍过了,请不要重复点击");
        }
//        根据砍价课程id查课程 拿数据 砍价的金额,和砍价的人数,并修改订单
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<TbPeopleCourse> peopleCourseQueryWrapper = new QueryWrapper<>();
        peopleCourseQueryWrapper.eq("peo_id", peopleId);
        TbPeopleCourse tbPeopleCourse = tbPeopleCourseMapper.selectOne(peopleCourseQueryWrapper);
        BigDecimal peoCouPrice = tbPeopleCourse.getPeoCouPrice();
        String string = peoCouPrice.toString();
        Integer CouPrice = Integer.valueOf(string); // 设置砍的价格
        BigDecimal peoPrice = tbPeopleCourse.getPeoPrice();  // 原价
        Date peoEndTime = tbPeopleCourse.getPeoEndTime();  // 结束时间
        String peoPeople = tbPeopleCourse.getPeoPeople();
        Integer People = Integer.valueOf(peoPeople);// 需要砍的人数
        Date date = new Date();
        if (date.getTime() > peoEndTime.getTime()){
            return Result.buildResult(ResultEnum.ERROR).setResult("对不起,时间已过期");
        }
//        Object price = redisTemplate.boundValueOps("price").get();
//        redisTemplate.delete("price");
        Object price1 = redisTemplate.boundValueOps("price").get();
        String s = price1.toString();
        String[] items = s.split(",");
        String split[] = items;
        List<String> list1 = Arrays.asList(split);
        List<String> arrList = new ArrayList<String>(list1);
        String s2 = arrList.get(0);
        Double aDouble = Double.valueOf(s2);
        BigDecimal bigDecimal = BigDecimal.valueOf(aDouble);
//
        Map<String, Object> map1 = new HashMap<>();
        QueryWrapper<TbPeopleCourseOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("pco_id", orderId);
        TbPeopleCourseOrder tbPeopleCourseOrder = tbPeopleCourseOrderMapper.selectOne(orderQueryWrapper);
        BigDecimal pcoPrice = tbPeopleCourseOrder.getPcoPrice();
//        减去砍的价格,一次次减
        BigDecimal subtract = pcoPrice.subtract(bigDecimal);
        arrList.remove(0);
        if (subtract == pcoPrice){
//            去跳转支付
            long orderNumber =  orderId;
            //  砍价支付
            String subject = "砍价支付";
            String body = "帮帮课堂砍价支付";
            BigDecimal price = subtract;

//            BigDecimal
            String s1 = payServiceFeign.alipayTradePagePay(orderNumber, price, subject, body);
            return Result.buildResult(ResultEnum.SUCCESS).setResult("恭喜您,砍价成功").setResult(s1);
        }else {
            return Result.buildResult(ResultEnum.SUCCESS).setResult(userId+"砍了一刀,请继续加油");
        }
    }


    @ApiOperation(value = "修改砍价订单信息") //  接口文档方法名
    @ApiImplicitParams({            //  接口文档  解释参数
            @ApiImplicitParam(name = "orderId",value = "订单id",required = true,paramType = "query"),
            @ApiImplicitParam(name = "bigMoney",value = "价格",required = true,paramType = "query"),
            @ApiImplicitParam(name = "trade_no",value = "流水号",required = true,paramType = "query")
    })
    @PostMapping("updateCourseOrder")
    public Result updateCourseOrder(@RequestParam String orderId, @RequestParam String bigMoney,@RequestParam String trade_no){
        Map<String, Object> map1 = new HashMap<>();
        QueryWrapper<TbPeopleCourseOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("pco_id", orderId);
        TbPeopleCourseOrder tbPeopleCourseOrder = tbPeopleCourseOrderMapper.selectOne(orderQueryWrapper);
        tbPeopleCourseOrder.setPcoWaterId(trade_no);
        tbPeopleCourseOrderMapper.updateById(tbPeopleCourseOrder);
        return Result.buildResult(ResultEnum.SUCCESS);
    }



}

